package cn.itsource.crm.web.controller;

import cn.itsource.crm.domain.Employee;
import cn.itsource.crm.domain.WxUser;
import cn.itsource.crm.service.IEmployeeService;
import cn.itsource.crm.service.IWxUserService;
import cn.itsource.shiro.utils.LoginUserUtil;
import cn.itsource.shiro.utils.MyUsernamePasswordToken;
import cn.itsource.util.AjaxResult;
import cn.itsource.util.HttpClientUtils;
import cn.itsource.util.WxConstants;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Controller
//@RequestMapping("/user")
@CrossOrigin
public class LoginController {

    @Autowired
    private IWxUserService wxUserService;

    @Autowired
    private IEmployeeService employeeService;

    /**
     * 认证
     * @param
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "用户认证",notes = "用户认证")
    @ApiImplicitParam(name = "companyName",value = "公司名参数",required = true,dataType = "String",paramType = "path")
    public AjaxResult login(@RequestBody Employee employee, HttpServletRequest req){
        //获取当前主体
        Subject subject = SecurityUtils.getSubject();
        //封装token
        MyUsernamePasswordToken token = new MyUsernamePasswordToken(employee.getUsername(),
                employee.getPassword());
        //调用login2方法进行登录
        return login2(token);

    }

    /**
     * 认证,免密登录
     * @param
     * @return
     */
    public AjaxResult login2(MyUsernamePasswordToken token){
        //获取当前主体
        Subject subject = SecurityUtils.getSubject();
        //判断主体是否认证过
        if (!subject.isAuthenticated()) {
            try {
                /*到realm中认证*/
                subject.login(token);
            } catch (UnknownAccountException e) {
                e.printStackTrace();
                return new AjaxResult("用户名不存在!");
            } catch (IncorrectCredentialsException e) {
                e.printStackTrace();
                return new AjaxResult("密码错误");
            } catch (AuthenticationException e) {
                e.printStackTrace();
                return new AjaxResult("其他异常");
            }

        }
        //拿到认证之后的用户
        Employee employee1 =  (Employee)subject.getPrincipal();
        /*存用户*/
        LoginUserUtil.setUser(employee1);
        AjaxResult ajaxResult = new AjaxResult();
        employee1.setPassword(null);
        //手动把jsessionid 返回到前台
        Serializable sessionId = subject.getSession().getId();
        System.out.println("sessionId"+sessionId);
        HashMap mp = new HashMap();
        mp.put("token",sessionId);
        mp.put("user",employee1);
        ajaxResult.setObjResult(mp);

        return ajaxResult ;
    }


    /**
     * 微信扫码登录后的回调路径，1.获取到code
     * 2.再通过code获取到ak--》3.再获取微信用户信息
     * @param code
     * @param state
     * @return
     */
    @RequestMapping(value = "/callback",method = RequestMethod.GET)
    public String callback(String code,String state){
        System.out.println(code+"++++++++++++++++++++++++++++++");
        System.out.println(state+"++++++++++++++++++++++++++++++");

        if (!StringUtils.isEmpty(code)&&"STATE".equals(state)){
            System.out.println("进来了");
            //获取accessToken
            String accessToekenUrl = WxConstants.ACCESSTOKEURL
                    .replace("APPID",WxConstants.APPID)
                    .replace("SECRET",WxConstants.APPSECRET)
                    .replace("CODE",code);

            try {
                //获取access_token所在的对象
                String jsonStr = HttpClientUtils.httpGet(accessToekenUrl, null);
                System.out.println("jsonStr---"+jsonStr);
                //accessToken拿到值
                String accessToken = (String)JSONObject.parseObject(jsonStr).get("access_token");

                //获取用户信息
                String userInfoUrl = WxConstants.USERINFOURL
                        .replace("ACCESS_TOKEN", accessToken);
                String userInfoStr = HttpClientUtils.httpGet(userInfoUrl, null);
                System.out.println("userInfoStr---"+userInfoStr);
                //转换成json对象
                JSONObject jsonObject = JSONObject.parseObject(userInfoStr);
                //获取openid
                String openid = (String) jsonObject.get("openid");
                //如果微信用户已经和员工进行绑定,直接登录
                System.out.println("wxUserService======="+wxUserService);
                WxUser wxUser = wxUserService.findByOpenid(openid);
                if (wxUser != null && wxUser.getEmpid() != null){//说明该微信用户已经绑定账号
                    System.out.println("呵呵");
                    //查询出employee对象，取出username
                    Employee employee = employeeService.findOne(wxUser.getEmpid());
                    //封装到自定义token中
                    MyUsernamePasswordToken myUsernamePasswordToken = new MyUsernamePasswordToken(employee.getUsername());
                    //免密登录
                    AjaxResult ajaxResult = login2(myUsernamePasswordToken);
                    //如果免密登录成功，跳转到首页
                    if (ajaxResult.getSuccess()){
                        Subject subject = SecurityUtils.getSubject();
                        //获取当前用户的tokenid
                        Serializable tokenid =subject.getSession().getId();
                        //获取当前用户的主题
                        Employee employee1 = (Employee) subject.getPrincipal();
                        //将用户名和头像封装起来，传给前端
                        String username = employee1.getUsername();
                        String headimgurl = wxUser.getHeadimgurl();
                        Map<String,String> map = new LinkedHashMap<>();
                        map.put("username", username);
                        map.put("headimgurl",headimgurl);
                        System.out.println("-----------------------------------------");
                        System.out.println(tokenid);

                        //如果免密登录成功那么久跳转到首页去  把主题和token存到前台的sission中去
                        return "redirect:http://localhost:8080/#/?user="+map+"tokenid"+tokenid;
                    }
                    return null;


                }else {
                    if (wxUser == null){
                        //如果微信用户还没有保存到数据库，则先添加到数据库，再进行绑定
                        //存放wxUser
                        WxUser wxUser1 = new WxUser();
                        String adress = jsonObject.get("country") +(String) jsonObject.get("province")+ jsonObject.get("city");
                        wxUser1.setCity(adress);
                        wxUser1.setHeadimgurl((String) jsonObject.get("headimgurl"));
                        wxUser1.setNickname((String) jsonObject.get("nickname"));
                        wxUser1.setOpenid(openid);
                        Integer sex = (Integer) jsonObject.get("sex");
                        wxUser1.setSex(sex == 1);
                        wxUser1.setUnionid((String) jsonObject.get("unionid"));

                        wxUserService.save(wxUser1);
                    }
                    System.out.println("呵呵呵");
                    //跳转到绑定页面
                    return "redirect:http://localhost:8080/#/bind?openid="+openid;


                }

            } catch (Exception e) {
                e.printStackTrace();
            }


        }


        return "redirect:http://localhost:8080/#/login";
    }

    /**
     * 绑定微信账号
     * @return
     */
    @RequestMapping(value = "/bind",method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult bind(@RequestBody Map map,HttpServletRequest req){
        Employee employee = new Employee();
        String username = (String) map.get("username");
        employee.setUsername(username);
        employee.setPassword((String) map.get("password"));
        //调用登录方法，如果登录成功，则将用户绑定到微信表中，否则提示用户错误信息
        AjaxResult ajaxResult = login(employee, req);
        System.out.println("ajaxResult---"+ajaxResult);
        if (ajaxResult.getSuccess()){
            //根据username查询Employee对象
            Employee employee1 = employeeService.getByUsername(username);
            //绑定信息到微信表
            WxUser wxUser = new WxUser();
            wxUser.setEmpid(employee1.getId());
            wxUser.setOpenid((String)map.get("openid"));
            wxUserService.saveEmpid(wxUser);
            return ajaxResult;
        }

        return new AjaxResult("用户名或密码错误");
    }

}
